package com.example.userservice.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

/**
 * （AI生成）
 */
@Slf4j
@Configuration
public class RabbitMQConfig {

    public static final String OPERATION_LOG_EXCHANGE = "operation-log-exchange";
    public static final String OPERATION_LOG_QUEUE = "operation-log-queue";
    public static final String OPERATION_LOG_ROUTING_KEY = "operation.log";

    @Bean
    public TopicExchange operationLogExchange() {
        return new TopicExchange(OPERATION_LOG_EXCHANGE, true, false);
    }

    @Bean
    public Queue operationLogQueue() {
        return QueueBuilder.durable(OPERATION_LOG_QUEUE).build();
    }

    @Bean
    public Binding operationLogBinding() {
        return BindingBuilder
                .bind(operationLogQueue())
                .to(operationLogExchange())
                .with(OPERATION_LOG_ROUTING_KEY);
    }
    
    /**
     * 配置消息转换器，支持JSON格式
     */
    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }
    
    /**
     * 配置RabbitTemplate - 开启发送确认
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(messageConverter());
        
        // 开启发送确认
        template.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.info("消息发送成功: " + correlationData);
            } else {
                log.error("消息发送失败: " + cause);
            }
        });
        
        // 开启返回确认（当消息无法路由到队列时触发）
        template.setReturnsCallback(returned -> {
            log.info("消息路由失败: " + returned.getMessage() +
                             ", 交换机: " + returned.getExchange() + 
                             ", 路由键: " + returned.getRoutingKey());
        });
        
        // 设置强制回调
        template.setMandatory(true);
        
        // 配置重试模板
        template.setRetryTemplate(retryTemplate());
        
        return template;
    }
    
    /**
     * 配置重试模板
     */
    @Bean
    public RetryTemplate retryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();
        
        // 重试策略：最多重试3次
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(3);
        retryTemplate.setRetryPolicy(retryPolicy);
        
        // 退避策略：指数退避
        ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
        backOffPolicy.setInitialInterval(1000); // 初始间隔1秒
        backOffPolicy.setMultiplier(2.0); // 倍数
        backOffPolicy.setMaxInterval(10000); // 最大间隔10秒
        retryTemplate.setBackOffPolicy(backOffPolicy);
        
        return retryTemplate;
    }
}
